package com.lagouedu.kucun.consumer;

import com.alibaba.fastjson.JSONObject;
import com.lagouedu.kucun.entity.Order;
import com.lagouedu.kucun.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class MessageListener implements MessageListenerConcurrently {

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        MessageExt ext = list.get(0);
        // 处理消息
        String msg = new String(ext.getBody());
        JSONObject jsonObject = JSONObject.parseObject(msg);
        // 生成订单信息
        Order order = new Order();
        order.setProductId(jsonObject.getInteger("productId"));
        order.setUserId(jsonObject.getInteger("userId"));
        orderRepository.save(order);
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
